package org.jeecg.modules.chexk.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import org.jeecg.common.util.RestUtil;
import org.jeecg.modules.chexk.controller.EasyEpcClientTest;
import org.jeecg.modules.chexk.entity.KuybChexk;
import org.jeecg.modules.chexk.mapper.KuybChexkMapper;
import org.jeecg.modules.chexk.service.IKuybChexkService;
import org.jeecg.modules.chexk.vo.*;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 车型库
 * @Author: jeecg-boot
 * @Date:   2021-09-09
 * @Version: V1.0
 */
@Slf4j
@Service
public class KuybChexkServiceImpl extends ServiceImpl<KuybChexkMapper, KuybChexk> implements IKuybChexkService {
    String appcode = "b21d1b42df5949bdbeb8f1c9f62a9ee7";

    @Override
    public VinChelxq queryChelxqByVin(String vin) {
//        String host = "https://jmfaceip.market.alicloudapi.com";
//        String path = "/vehicle/vin-query";
//        String method = "POST";
//
//        Map<String, String> headers = new HashMap<String, String>();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        //根据API的要求，定义相对应的Content-Type
//        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//        Map<String, String> querys = new HashMap<String, String>();
//        Map<String, String> bodys = new HashMap<String, String>();
//        bodys.put("vin", vin);
//
//        try {
//            /**
//             * 重要提示如下:
//             * HttpUtils请从
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
//             * 下载
//             *
//             * 相应的依赖请参照
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
//             */
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
//            //获取response的body
//            String rtn = EntityUtils.toString(response.getEntity());
//            VinChelxq vinChelxq = JSON.parseObject(rtn, new TypeReference<VinChelxq>() {});
//            if(vinChelxq != null)
//                return vinChelxq;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        String host = "https://www.easyepc.com";
        String path = "/vf/api/";
        String apiCode = "500020";
        String url = host + path + apiCode;
        //请求头信息
        Map<String, String> head = new HashMap<String, String>();
        head.put("uacId", "283a87y3IqFS");
        head.put("password", "cdcc81addbe1160d2ba558ebf1931104");
        //请求参数
        Map<String, String> body = new HashMap<String, String>();
        body.put("vin", vin);

        try {
            String returnData = EasyEpcClientTest.getData(url, head, body);
            log.info(returnData);
            VinChelxq vinChelxq = JSON.parseObject(returnData, new TypeReference<VinChelxq>() {});
            if(vinChelxq != null)
                return vinChelxq;

        } catch (Exception e) {
            log.error("接口"+apiCode+"调用出现异常,信息为："+e.getMessage());
        }

        return null;
    }

    @Override
    public List<Brand> getBrandList() {
        String host = "https://jumcarr.market.alicloudapi.com";
        String path = "/vehicle/query/brand";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            String rtn = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(rtn);
            if(jsonObject != null) {
                List<Brand> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Brand>>() {});
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Series> getSeriesList(String brandId) {
        String host = "https://jumcarr.market.alicloudapi.com";
        String path = "/vehicle/query/series";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("brandId", brandId);

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));

            String rtn = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(rtn);
            if(jsonObject != null) {
                List<Series> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Series>>() {});
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<Model> getModelList(String seriesId) {
        String host = "https://jumcarr.market.alicloudapi.com";
        String path = "/vehicle/query/model";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("seriesId", seriesId);
        bodys.put("sort", "yearr");

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            String rtn = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(rtn);
            if(jsonObject != null && jsonObject.getString("code").equals("200")) {
                List<Model> list = JSON.parseObject(jsonObject.getJSONObject("data").getString("list"), new TypeReference<List<Model>>() {});
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    String client_id = "qYsnnFXEOls1N1kGaUrYMDjU";
    String client_secret = "rKYUNLzfHY69Z5fOnI7gNrfCgNqnMNBL";
    String getBaiduAccessToekn() {
        JSONObject jsonObject = RestUtil.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret);
        if(jsonObject != null) {
            return jsonObject.getString("access_token");
        }

        return "";
    }

    @Override
    public OcrCarData baiduOcrCarData(String type, HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象

            // 请求url
            String url = null;
            if(type.equals("vin"))
                url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vin_code";
            else
                url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license";

            try {
                // 本地文件路径
                String filePath = "[本地文件路径]";
                String imgStr = Base64Util.encode(file.getBytes());
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");

                String param = "image=" + imgParam;

                // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
                String accessToken = getBaiduAccessToekn();

                String result = HttpUtil.post(url, accessToken, param);
                OcrCarData ocrCarData = new OcrCarData();
                if(type.equals("vin")) {
                    ocrCarData = JSON.parseObject(result, new TypeReference<OcrCarData>() {});
                    if(ocrCarData.getWords_result() != null) {
                        String vin = ocrCarData.getWords_result().get(0).getWords();
                        ocrCarData.setVinCode(vin);

                    } else
                        throw new RuntimeException("识别失败");
                }
                else {
                    OcrCarData2 ocrCarData2 = JSON.parseObject(result, new TypeReference<OcrCarData2>() {});
                    if(ocrCarData2.getError_code() != null && ocrCarData2.getError_code().equals("216202"))
                        throw new RuntimeException("选择的图片尺寸太大, 换一张小点的图片");

                    if(ocrCarData2.getWords_result() != null) {
                        VehicleLicense vehicleLicense = new VehicleLicense();
                        vehicleLicense.setChelsbdh(ocrCarData2.getWords_result().get车辆识别代号().getWords());
                        vehicleLicense.setZhuz(ocrCarData2.getWords_result().get住址().getWords());
                        vehicleLicense.setFazdw(ocrCarData2.getWords_result().get发证单位().getWords());
                        vehicleLicense.setChellx(ocrCarData2.getWords_result().get车辆类型().getWords());
                        vehicleLicense.setPinpxh(ocrCarData2.getWords_result().get品牌型号().getWords());
                        vehicleLicense.setFazrq(ocrCarData2.getWords_result().get发证日期().getWords());
                        vehicleLicense.setSuoyr(ocrCarData2.getWords_result().get所有人().getWords());
                        vehicleLicense.setHaophm(ocrCarData2.getWords_result().get号牌号码().getWords());
                        vehicleLicense.setShiyxz(ocrCarData2.getWords_result().get使用性质().getWords());
                        vehicleLicense.setFadjhm(ocrCarData2.getWords_result().get发动机号码().getWords());
                        vehicleLicense.setZhucrq(ocrCarData2.getWords_result().get注册日期().getWords());

                        ocrCarData.setVinCode(vehicleLicense.getChelsbdh());
                        ocrCarData.setVehicleLicense(vehicleLicense);
                    }
                }

                return ocrCarData;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Data queryCarBasicByCarId(String carId) {
        Data d=new Data();
        String host = "https://jumcarr.market.alicloudapi.com";
        String path = "/vehicle/query/detail";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("modelId", carId);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());

            String rtn = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(rtn);
            if(jsonObject != null && jsonObject.getString("code").equals("200")) {
                 d = JSON.parseObject(jsonObject.getString("data"), new TypeReference<Data>() {});
                return d;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }

    public static void main(String[] args) {
        KuybChexkServiceImpl service=new KuybChexkServiceImpl();
        Data d= service.queryCarBasicByCarId("5499");
    }
}
